const express = require('express')
const router = express.Router()
const sys_user = require('../../models/sys_user')
const { formatDateTime } = require('../../utils/dateUtils')

router.post('/user/heartbeat', async (req, res) => {
    try {
        const { userId } = req.body

        if (userId) {
            await sys_user.updateLastActiveTime(userId, new Date())
        }

        const userRes = await sys_user.findUserById(userId)
        const user = {
            "id": userRes.id,
            "user_name": userRes.user_name,
            "real_name": userRes.real_name,
            "password": userRes.password,
            "salt": userRes.salt,
            "role_ids": userRes.role_ids,
            "depart_id": userRes.depart_id,
            "create_time": formatDateTime(userRes.create_time),
            "update_time": formatDateTime(userRes.update_time),
            "state": userRes.state,
            "data_flag": userRes.data_flag,
            "last_active_time": formatDateTime(userRes.last_active_time)
        }

        return res.json({
            msg: "心跳数据接收成功，用户当前还在线",
            data: user,
            code: 0,
            success: true
        });
    } catch (error) {
        console.error('数据库操作错误', error)
        return res.status(500).json({
            msg: 'Internal server error',
            code: 500,
            success: false
        })
    }
})

module.exports = router
